import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hixing_app/assets/r_img.dart';

class TestPaintShader extends StatefulWidget {
  const TestPaintShader({super.key});

  @override
  TestPaintShaderState createState() => TestPaintShaderState();
}

class TestPaintShaderState extends State<TestPaintShader> {
  ui.Image? imgData;
  ui.FragmentShader? shader;

  Future<void> loadImg() async {
    var img = await loadImageFromAssets(ImgR.imgBgDog);

    setState(() {
      imgData = img;
    });
  }

  Future<ui.Image>? loadImageFromAssets(String path) async {
    ByteData data = await rootBundle.load(path);
    return decodeImageFromList(data.buffer.asUint8List());
  }

  void _loadShader() async {
    await loadImg();
    String path = 'shaders/dogs.frag';
    ui.FragmentProgram program = await ui.FragmentProgram.fromAsset(path);

    shader = program.fragmentShader();
    // print("当前的shader:${program.fragmentShader()}");
    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _loadShader();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('画笔shader模板'),
      ),
      body: Container(
        width: 200,
        height: 200,
        child: CustomPaint(
          size: ui.Size(200, 200),
          painter: MyPainter(img: imgData, shader: shader),
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  MyPainter({this.img, this.shader});

  ui.Image? img;
  ui.FragmentShader? shader;

  @override
  void paint(ui.Canvas canvas, ui.Size size) {
    ui.Paint paint = ui.Paint();
    if (shader != null) {
      shader!.setFloat(0, size.width + 100);
      shader!.setFloat(1, size.height + 100);
      shader!.setImageSampler(0, img!);
      paint.shader = shader;
    }
    canvas.drawRect(
      Rect.fromLTWH(0, 0, size.width + 100, size.height + 100),
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

void resizeImg(Canvas canvas, Size size, ui.Image img, Paint paint,
    {double x = 0, double y = 0}) {
  double cmpWidth = 0;
  double cmpHeight = 0;
  if (img.width > img.height) {
    cmpHeight = (size.width / img.width) * img.height;
  } else if (img.width < img.height) {
    cmpWidth = (size.height / img.height) * img.width;
  }
  double renderWidth = cmpWidth == 0 ? size.width : cmpWidth;
  double renderHeight = cmpHeight == 0 ? size.height : cmpHeight;

  // Draw image with scaled width
  canvas.drawImageRect(
    img,
    Rect.fromLTRB(0, 0, img.width.toDouble(), img.height.toDouble()),
    // 如果要居中，就调这里的 x，y值
    Rect.fromLTRB(x, -renderHeight, renderWidth, 0),
    Paint(),
  );
}
